<template>
  <el-dialog v-model="associatedUsersVisible" title="关联用户" width="500">
    <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange">全选</el-checkbox>
    <el-checkbox-group v-model="checkedUsers" @change="handlecheckedUsersChange">
      <el-checkbox v-for="user in users" :key="user.id" :label="user.name" :value="user.id">
        {{ user.name }}
      </el-checkbox>
    </el-checkbox-group>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="submit" :loading="loading">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="AssociatedUsers">
import { ref } from "vue";
import { getUserList } from "@/api/modules/userManagement";
import { roleAssociatedUser, getRoleDetail } from "@/api/modules/roleManagement";
import { ElMessage } from "element-plus";

// 角色id
let roleId: any = 0;
// emit
// const emit = defineEmits<{
//   submit: [value: any];
// }>();
let loading = false;
const checkAll = ref(false);
const isIndeterminate = ref(true);
const checkedUsers = ref<any[]>([]);
let users = ref<any[]>([]);
// 关联用户
const associatedUsersVisible = ref<boolean>(false);
const openDialog = id => {
  roleId = id;
  loading = false;
  associatedUsersVisible.value = true;
  getUsers();
  getDetail();
};
const closeDialog = () => {
  loading = false;
  associatedUsersVisible.value = false;
};

const handleCheckAllChange: any = (val: boolean) => {
  if (val) {
    checkedUsers.value = users.value.map(item => {
      return item.id;
    });
  } else {
    checkedUsers.value = [];
  }
  isIndeterminate.value = false;
};
const handlecheckedUsersChange: any = (value: string[]) => {
  const checkedCount = value.length;
  checkAll.value = checkedCount === users.value.length;
  isIndeterminate.value = checkedCount > 0 && checkedCount < users.value.length;
};
// 获取用户列表
const getUsers = async () => {
  const { data } = await getUserList({ page: 1, page_size: 10000 });
  users.value = data.results;
};
// 获取角色详情
const getDetail = async () => {
  checkedUsers.value = [];
  const { data } = await getRoleDetail(roleId);
  checkedUsers.value = data.user_ids;
};
const submit = async () => {
  loading = true;
  const { data } = await roleAssociatedUser(roleId, { ids: checkedUsers.value });
  loading = false;
  if (data) {
    ElMessage({
      type: "success",
      message: `操作成功!`
    });
    associatedUsersVisible.value = false;
  }
};
defineExpose({
  openDialog,
  closeDialog
});
</script>
